import {ref,Ref,onMounted,onUnmounted, watchEffect} from 'vue'

const useClickOutside = (elementRef: Ref<null | HTMLElement>) =>{
    const isClickOutside = ref(false)
    const handler = (e:MouseEvent) =>{
        if(elementRef.value){
            if(elementRef.value.contains(e.target as HTMLElement)){
                isClickOutside.value = false
            }else{
                isClickOutside.value = true
            }
        }
    }
    //  //当挂载的时候绑定监听函数
    //  onMounted(()=>{
    //     document.addEventListener('click',handler)
    // })
    // //当销毁的时候去除监听函数
    // onUnmounted(() =>{
    //     document.removeEventListener('click',handler)
    // })
    watchEffect((onCleanup)=>{
        document.addEventListener('click',handler)
        onCleanup(()=>{
            document.removeEventListener('click',handler)
        })
    })
    return isClickOutside
}

export default useClickOutside